package com.zx.web.dao.impl;

import com.zx.bean.User;
import com.zx.utils.DataSourceUtils;
import com.zx.web.dao.UserDao;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

/**
 * @author 章鑫
 * @version V1.0
 * @Project 2022-09-05
 * @Package com.zx.web.dao.impl
 * @Description:
 * @Date 2022/9/13 14:19
 */
public class UserDaoImpl implements UserDao {
    private QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
    @Override
    public User findByUserName(String username) {
        String sql = "select * from tb_user where username=?";
        try {
            return qr.query(sql, new BeanHandler<>(User.class),username);
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean register(User user) {
        String sql = "INSERT INTO `tb_user`(`username`,`password`,`email`,`gender`,`flag`,`role`) VALUES (?,md5(?),?,?,?,?);";
        try {
            int result = qr.update(sql,user.getUsername(),user.getPassword(),user.getEmail(),user.getGender(),user.getFlag(),user.getRole());
            return result>0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }

    @Override
    public User findByUserAndPwd(String username, String password) {
        String sql = "select * from tb_user where username=? and password = md5(?)";
        try {
            return qr.query(sql,new BeanHandler<>(User.class),username,password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
}
